const fs = require('fs');
const path = require('path');
const ds = require('./tools/tool');
const tool = require('./tools/tool');

async function getAllModules() {
    const modulesDir = path.join(__dirname, 'modules');
    let parsedModules = [];
    const files = await fs.promises.readdir(modulesDir);

    await Promise.all(files.map(async (file) => {
        if (path.extname(file) === '.js') {
            const modulePath = path.join(modulesDir, file);
            const module = require(modulePath);
            if (typeof module === 'object') {
                parsedModules.push({
                    file: file.replace('.js', ''),
                    o: {
                        ...module
                    }
                });
            }
        }
    }));
    return parsedModules;
}

module.exports = async () => {
    let modules = await getAllModules()
    let parsedPorts = []
    let re = {}
    for (let i = 0; i < modules.length; i++) {
        let module = modules[i]
        re[module.file] = module.o
    }
    const parseAllPorts = (o, currentName = '') => {
        ds.object.for(o, (k, v) => {
            if (v.func == undefined) {
                parseAllPorts(v, currentName + '/' + k)
            } else {
                let c = {
                    api: currentName + '/' + k,
                    ...v
                }
                parsedPorts.push(c)
            }
        })
    }
    parseAllPorts(re, ``)
    await tool.wait(0.1)
    return parsedPorts
}